<template>
    <div class=''>
        <!-- 实验信息 -->
        <h2>样品信息</h2>
        <!-- :rules="registerRule" -->
        <Form :model="recordMsg"  :rules="recordRule" ref="recordForm">
            <FormItem prop="recordName" label="样品编号">
                <Input type="text" v-model="recordMsg.recordName" :disabled="true"></Input>
            </FormItem>
            <FormItem prop="type" label="基底类型">
                <Input v-model="recordMsg.type" :disabled="false"></Input>
            </FormItem>
            <FormItem prop="material" label="样品材料">
                <Input v-model="recordMsg.material" :disabled="false"></Input>
            </FormItem>
            <FormItem prop="conditions" label="反应条件">
                <Input v-model="recordMsg.conditions" :disabled="false"></Input>
            </FormItem>
            <FormItem prop="weight" label="样品增重">
                <Input v-model="recordMsg.weight" :disabled="false"></Input>
            </FormItem>
            <FormItem  label="状态">
                <!-- <Input v-model="experimentMsg.status"></Input> -->
                <i-switch v-model="recordMsg.status" :disabled="false"></i-switch>  
            </FormItem>
            <FormItem  label="备注信息">
                <!-- <Input v-model="experimentMsg.content"></Input> -->
                <Input v-model="recordMsg.content" type="textarea" :disabled="false"></Input>
            </FormItem>
            <FormItem>
                <h3>相关图片</h3>
                <div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">
                    <template v-if="item.status === 'finished'">
                        <img :src="item.src">
                        <div class="demo-upload-list-cover">
                            <Icon type="ios-eye-outline" @click.native="handleView(item.src)"></Icon>
                            <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                        </div>
                    </template>
                    <template v-else>
                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                </div>
                <Upload
                    ref="upload"                   
                    :data="dataObj"
                    :show-upload-list="false"
                    :on-success="handleSuccess"
                    :format="['jpg','jpeg','png']"
                    :on-format-error="handleFormatError"
                    :before-upload="handleBeforeUpload"
                    multiple
                    type="drag"
                    action="http://laboratory101.oss-cn-hangzhou.aliyuncs.com"
                    style="display: inline-block;width:58px;">
                    <div style="width: 58px;height:58px;line-height: 58px;">
                        <Icon type="ios-camera" size="20"></Icon>
                    </div>
                </Upload>
                <Modal title="查看图片" v-model="visible">
                    <img :src="curSrc" v-if="visible" style="width: 100%">
                </Modal>                
            </FormItem>
            <FormItem>
                <Button type="primary" @click="save">保存</Button>
                <Button type="primary" @click="back">返回</Button>
            </FormItem>
        </Form>            
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {getUUID} from '@/utils/index.js'
export default {
//import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        return {
            //实验信息
            recordId:'',
            recordMsg:{
              content: '',
              recordId: '',
              recordName: '',
              status: false,
              type: '',
              material:'',
              conditions:'',
              weight:'',
              experimentId: '',
              imgs:[]  
            },
            recordRule:{
                recordName:[
                    { required: true, message: 'Please fill in the recordName', trigger: 'blur' }
                ],
                type:[
                    { required: true, message: 'Please fill in the type', trigger: 'blur' }
                ]
            },
            backInfo:{

            },
            //1.图片上传所需信息
            dataObj:{
              policy:'',
              signature:'',
              ossaccessKeyId:'',
              key:'',
              dir:'',
              host:''
            },
            curSrc: '',
            visible: false,
            uploadList: []            
        };
    },
    created(){
        this.recordId = this.$route.query.recordMsg.recordId
        this.backInfo = this.$route.query.experimentMsg
        this.getRecordFile(this.recordId)
    },
    mounted(){
        this.uploadList = this.$refs.upload.fileList;
    },
    methods: {    
        //通过recordId向后端发送请求获取所有信息
        async getRecordFile(id){
            const {data:res} = await this.$axios.get('/record/message/'+ id)
            console.log(res)
            if(res.status == 200){
                this.recordMsg = res.data
                for(let i = 0; i < this.recordMsg.imgs.length; i++){
                    this.$refs.upload.fileList.push({
                        // name: "TCP断开连接的四次挥手.png",
                        // percentage: 100,
                        // response: "",
                        // showProgress: false,
                        // size: 35147,
                        src: this.recordMsg.imgs[i],
                        status: "finished",
                        // uid: 1624932941657   ,     
                    })
                }
            }
        },
        async handleBeforeUpload () {
           await this.beforeUpload()
        },
        async beforeUpload(){
          const {data:response} = await this.$axios.post('/oss/policy')
          this.dataObj.policy = response.data.policy;
          this.dataObj.signature = response.data.signature;
          this.dataObj.ossaccessKeyId = response.data.accessid;
          this.dataObj.key = response.data.dir + getUUID() + '_${filename}';
          this.dataObj.dir = response.data.dir;
          this.dataObj.host = response.data.host;  
        },   
        handleFormatError (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleSuccess (res, file) {
            file.src = this.dataObj.host + '/' + this.dataObj.key.replace('${filename}',file.name) 
            console.log(this.$refs.upload.fileList)
        },
        //查看图片
        handleView (src) {
            this.curSrc = src;
            this.visible = true;
        },
        // 删除图片
        handleRemove (file) {
            // 从 upload 实例删除数据
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
        },
        async save(){
            this.$refs.recordForm.validate(async (valid) => {
                if(valid){
                    let imgs = []
                    for(let item of this.$refs.upload.fileList){
                        imgs.push(item.src)
                    }
                    this.recordMsg.imgs = imgs
                    // console.log(this.backInfo)
                    this.recordMsg.experimentId = this.backInfo.id
                    const {data:res} = await this.$axios.post('/record/update', this.recordMsg)
                    if(res.status == 200){
                        this.$Message.info(res.msg)
                        this.back()
                    }else{
                        this.$Message.info(res.msg)
                    }
                }
            })
        },
        back(){
            this.$router.push({
                path:'/admin/editexperiment',
                query:{
                   experimentMsg:this.backInfo
                }
            })
        }
    },

}
</script>
<style>
  .ivu-form{
    margin:0 1vw
  }
  h2{
    margin:1vw 2vh
  }
  .demo-upload-list{
    width:250px !important;
    height:250px  !important;
    margin-right:3vw !important;
  }
  .ivu-modal{
     width:50% !important; 
  }
  /* 上传图片 */
  .demo-upload-list{
      display: inline-block;
      width: 60px;
      height: 60px;
      text-align: center;
      line-height: 60px;
      border: 1px solid transparent;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      box-shadow: 0 1px 1px rgba(0,0,0,.2);
      margin-right: 4px;
  }
  .demo-upload-list img{
      width: 100%;
      height: 100%;
  }
  .demo-upload-list-cover{
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
      display: block;
  }
  .demo-upload-list-cover i{
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 2px;
  }
</style>